<template>
  <div class="numInputs">
    <input
      v-for="(n, index) in amount"
      v-model="arr[index]"
      maxlength="1"
      @keyup="nextFocus($event, index)"
      ref="numInput"
      type="tel"
      :key="index"
    />
  </div>
</template>
<script>
export default {
  props: {
    amount: {
      default: 6,
      type: Number
    }
  },
  data () {
    return {
      arr: []
    }
  },
  created () {
    setTimeout(() => {
      this.$refs.numInput[0] && this.$refs.numInput[0].focus()
    }, 0)
  },
  watch: {
    arr (val) {
      this.$emit('input', val.join(''))
    }
  },
  methods: {
    nextFocus ($event, index) {
      // 键入时光标跳转
      this.arr[index] &&
        this.$refs.numInput[index + 1] &&
        this.$refs.numInput[index + 1].focus()
      // 删除
      if ($event.keyCode === 8) {
        if (this.arr[index]) {
          this.arr[index] = ''
          this.arr = JSON.parse(JSON.stringify(this.arr))
          this.$refs.numInput[index].focus()
        } else {
          this.$refs.numInput[index - 1] &&
            this.$refs.numInput[index - 1].focus()
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.numInputs {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  input {
    border: none;
    width: 40px;
    height: 40px;
    line-height: 40px;
    border-bottom: 1px solid rgba(221, 221, 221, 1);
    font-size: 18px;
    color: #2b293a;
    line-height: 21px;
    text-align: center;
  }
}
</style>
